﻿using Faser_VoteSys.Models.Database;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System;
using Faser_VoteSys.Common;
using Faser_VoteSys.Configs;

namespace Faser_VoteSys.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class InformationController : Controller
    {
        private readonly Faser_VoteSysContext _db;
        private readonly Services.IJWTService _jwtService;

        public InformationController(Faser_VoteSysContext db, Services.IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }

        [HttpPost]
        public async Task<IActionResult> UploadImage(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return ApiError.NO_FILE_UPLOADED;
            }

            var allowedExtensions = new[] { ".jpeg", ".jpg", ".png", ".webp" };
            var extension = Path.GetExtension(file.FileName).ToLowerInvariant();

            if (!allowedExtensions.Contains(extension))
            {
                return ApiError.UNSUPPORTED_FILE_TYPE;
            }

            try
            {
                var fileName = GenerateFileName(file);
                var filePath = Path.Combine(PathConfigurator.UPLOADS_FOLDER_PATH, fileName);

                if (System.IO.File.Exists(filePath))
                {
                    return Ok(fileName);
                }

                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                return Ok(fileName);
            }
            catch (Exception ex)
            {
                return ApiError.ServerInternalError(ex.Message);
            }
        }

        private string GenerateFileName(IFormFile file)
        {
            using (var sha256 = SHA256.Create())
            {
                var hash = sha256.ComputeHash(file.OpenReadStream());
                var hashString = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
                return $"{hashString}{Path.GetExtension(file.FileName)}";
            }
        }

    }
}
